package cn.ncucode.blog.controller;

import cn.ncucode.blog.model.Category;
import cn.ncucode.blog.model.Resources;
import cn.ncucode.blog.model.User;
import cn.ncucode.blog.service.ResourcesService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.sql.Timestamp;
import java.util.List;

@Controller
@RequestMapping("res")
public class ResourcesController {

    @Autowired
    @Qualifier("resourcesServiceImpl")
    private ResourcesService resourcesService;

    //因为 request.getSession().getServletContext().getRealPath("") 获取到的是 项目target下的目录 这里只好把目录写死来。。。
    private final String resPath = "E:\\大三（下）\\项目实战 - 博客管理系统\\gitee\\Blog1\\src\\main\\webapp\\user\\resources";



    //@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
    //批量上传CommonsMultipartFile则为数组即可
    @PostMapping("uploadRes")
    @ResponseBody  //返回值  不走视图解析器
    public int uploadRes(String resName, double size, String type, String dsb, int category, int scores,
                         @RequestParam("file") CommonsMultipartFile file, HttpSession session, HttpServletRequest request){
        int success = 1;  //标志是否上传成功  1 表示成功，  0表示失败
        Resources resources = new Resources();
        Timestamp uploadTime = new Timestamp(new Date().getTime());  //文件上传时间 使用Timestamp 类型可以写入时分秒

        //此处从前端获取到的是资源对应分类的分类id
        resources.setCategory(new Category(category));
        resources.setResName(resName);
        resources.setSize(size);
        resources.setType(type);
        resources.setDsb(dsb);
        resources.setScores(scores);

//        session.getAttribute(""); 从session获取user 的id
        resources.setUploader(new User((long)100002));
        //通过 util包下的 Date（可直接获取系统时间） 实例化 sql包下的Date
        resources.setUploadTime(uploadTime);

        //上传文件之后再向数据库插入数据   这个过程是一个事务 要保持原子性
        File realPath = new File(resPath);
        if (!realPath.exists())  //如果该路径不存在则创建它
        {
            realPath.mkdir();
        }
        try {
            file.transferTo(new File(realPath + "/" + resources.getUploader().getUserid() + "_" + file.getOriginalFilename()));
            resources.setPath(resources.getUploader().getUserid() + "_" + file.getOriginalFilename()); //写入的是文件名（uid_原文件名），而不是整个文件存放的路径，  读取的时候直接用路径变量拼接即可

            int rs = resourcesService.addResources(resources);
            if (rs < 1) {  //受影响行数 如果小于1（正常应该是等于1） 则说明插入失败
                success = 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
            success = 0;
            System.out.println("文件写入或者数据库写入抛出异常！ 上传资源失败！");
        }


//        resources.setPath(path);
        //获取tomcat下的resources目录的路径 注意它读取的target下的目录   E:\大三（下）\项目实战 - 博客管理系统\gitee\Blog1\target\Blog1.0\resources
//        System.out.println("servletContext getRealPath(): " + request.getSession().getServletContext().getRealPath(""));
//        System.out.println("上传文件原名：" + file.getOriginalFilename());
//        System.out.println("后端获取的getSize:" + file.getSize());  //获取到的文件大小和前端获取到的时一样的
//        System.out.println("后端获取的getBytes:" + file.getBytes());  //后端获取的getBytes:[B@5d271e35

        System.out.println("resName: " + resName);
        System.out.println("size: " + size);
        System.out.println("type: " + type);
        System.out.println("dsb: " + dsb);
        System.out.println("category: " + category);
        System.out.println("scores: " + scores);

        return success;
    }


    //根据用户id查询该用户已上传的资源
    @RequestMapping("myres")
    public String showUserResources(Model model, HttpSession session){
//        session.getAttribute();  //获取userid
        long userId = 100001;
        List<Resources> resList = resourcesService.getResourcesByUserId(userId);
        if (resList == null){
            System.out.println("resList为 null");
        }else {
            System.out.println("resList的size：" + resList.size());
        }

        model.addAttribute("myRes", resList);
        return "user/myres";
    }

    @Test
    public void testGetAllResources(){
        System.out.println("_________________________");
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println("_________________________");

        ResourcesService resourcesServiceImpl = applicationContext.getBean("resourcesServiceImpl", ResourcesService.class);
        for (Resources resource : resourcesServiceImpl.getAllResources()) {
            System.out.println(resource);
        }
    }

    @Test
    public void test(){
        System.out.println("0对3取余：" + 0%3);
    }
}
